package com.mdg.bike;

import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;

public class Map extends MapActivity {

	private Context mCon;
	private PathOverlay po;
	private Handler mHandler = new Handler();
	private Runnable mUpdateTask;
	private long mStartTime = 0L;
	private MyLocationOverlay myLocOverlay;
	MapView mv;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);

		mCon = this;
		
		mv = (MapView) findViewById(R.id.mapview);
		mv.setBuiltInZoomControls(true);
		mv.setSatellite(true);
		mv.setClickable(true);
		po = new PathOverlay(mCon);
		mv.getOverlays().add(po);
	
        mUpdateTask = new Runnable() {
        	   public void run() {
        	     
        	       long delay = 2000;
        	       mHandler.postDelayed(this, delay);

        	       GeoPoint point = myLocOverlay.getMyLocation();
        	       if(point != null){
        	    	   po.addPathPoint(point);
        	    	   mv.invalidate();
        	       }
        	}
        };
        	
        myLocOverlay = new MyLocationOverlay(this, mv);
        myLocOverlay.runOnFirstFix(new Runnable(){

        	public void run() {
        		MapController mc = mv.getController();
        		mc.setZoom(16);
        		mv.getController().animateTo(myLocOverlay.getMyLocation());
        	}
    			
        });
        
        StartLoggingLocations();
}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
    public void StartLoggingLocations(){
    	if(!(myLocOverlay.isMyLocationEnabled())){
    		if(myLocOverlay.enableMyLocation()){
    			List<Overlay> mapOverlays = mv.getOverlays();
    			
    			mapOverlays.add(myLocOverlay);
    			
    			mv.invalidate();
    			
    			if (mStartTime == 0L) {
    	            mStartTime = System.currentTimeMillis();
    	            mHandler.removeCallbacks(mUpdateTask);
    	            mHandler.postDelayed(mUpdateTask, 100);
    	       }
    		}
    		else{
    			System.err.println("Failed to enable the current location");
    		}
    	}
    }
    
    public void StopLoggingLocations(){
    	if(myLocOverlay.isMyLocationEnabled()){
    		List<Overlay> mapOverlays = mv.getOverlays();
			
			mapOverlays.remove(myLocOverlay);
			
			mv.invalidate();
			
    		myLocOverlay.disableMyLocation();
    		
    		mHandler.removeCallbacks(mUpdateTask);
    	}
    }
}
